package com.lhfeiyu.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.config.Assets;
import com.lhfeiyu.config.Const;
import com.lhfeiyu.config.base.BaseAssets;
import com.lhfeiyu.dao.AuctionGoodsMapper;
import com.lhfeiyu.dao.AuctionProfessionMapper;
import com.lhfeiyu.dao.base.BaseGoodsMapper;
import com.lhfeiyu.dao.base.BaseGoodsPictureMapper;
import com.lhfeiyu.dao.base.BaseShopMapper;
import com.lhfeiyu.dao.base.BaseUserMapper;
import com.lhfeiyu.domain.base.AliyunOSS;
import com.lhfeiyu.po.AuctionGoods;
import com.lhfeiyu.po.AuctionProfession;
import com.lhfeiyu.po.base.BaseGoods;
import com.lhfeiyu.po.base.BaseGoodsPicture;
import com.lhfeiyu.po.base.BaseShop;
import com.lhfeiyu.po.base.BaseUser;
import com.lhfeiyu.service.base.BaseGoodsService;
import com.lhfeiyu.service.base.BaseNoticeService;
import com.lhfeiyu.service.base.BasePictureService;
import com.lhfeiyu.tools.base.Check;
import com.lhfeiyu.tools.base.CommonGenerator;
import com.lhfeiyu.tools.base.Result;
import com.lhfeiyu.util.base.Utf8mb4;

/**
* <strong> 描&nbsp;&nbsp;&nbsp;&nbsp;述：</strong> 业务层：Goods <p>
* <strong> 作&nbsp;&nbsp;&nbsp;&nbsp;者：</strong> 虞荣华  <p>
* <strong> 编写时间：</strong>2016年3月20日22:22:22<p>
* <strong> 公&nbsp;&nbsp;&nbsp;&nbsp;司：</strong> 成都蓝海飞鱼科技有限公司 http://lhfeiyu.com <p>
* <strong> 版&nbsp;&nbsp;&nbsp;&nbsp;本：</strong> 2.0 <p>
* <strong> 备&nbsp;&nbsp;&nbsp;&nbsp;注：</strong> 继承基础库中的GoodsService <p>
 */
@Service
public class GoodsService extends BaseGoodsService {
	
	@Autowired
	BaseUserMapper userMapper;
	@Autowired
	BaseGoodsMapper goodsMapper;
	@Autowired
	BaseShopMapper shopMapper;
	@Autowired
	BaseNoticeService noticeService;
	@Autowired
	BaseGoodsPictureMapper goodsPictureMapper;
	@Autowired
	BasePictureService pictureService;
	@Autowired
	AuctionGoodsMapper agMapper;
	@Autowired
	AuctionProfessionMapper apMapper;
	
	public JSONObject getGoodsList(JSONObject json, Map<String, Object> map) {
		return super.getGoodsListSimple(json, map);
	}

	public JSONObject updateGoodsBase(JSONObject json, BaseGoods goods, BaseUser user){
		Integer userId = user.getId();
		String username = user.getUsername();
		if(null == goods || Check.isNull(goods.getId())){
			Result.failure(json, "请选择藏品", "goodsId_null");
		}
		BaseGoods dbGoods = goodsMapper.selectByPrimaryKey(goods.getId());
		if(null == goods || Check.isNull(goods.getId())){
			Result.failure(json, "藏品不存在", "goods_null");
		}
		Integer goodsUserId = dbGoods.getUserId();
		if(!Check.integerEqual(userId, goodsUserId)){
			Result.failure(json, "该藏品不属于您，您没有权限进行修改", "auth_failure");
		}
		
		return super.updateGoodsSimple(json, goods, username);
	}
	
	private JSONObject validateGoods(JSONObject json, BaseGoods goods){
		/* 判断用户是否被禁止发布藏品，后期开通
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userId", userId);
		map.put("controlTypeId", 55);
		map.put("controlDate", 1);
		int userControlList = userControlService.selectCountByCondition(map);
		if(userControlList > 0){
			json.put("status", "failure");
			json.put("msg", "您被禁止进行商品添加,请联系管理员解除限制.");
			return json;
		}*/
		if(Check.isNull(goods.getGoodsName()) ){
			return Result.failure(json, "商品名称不能为空", "goodsName_null");
		}
		if(Check.isNull(goods.getGoodsBrief())){
			return Result.failure(json, "商品描述不能为空", "goodsBrief_null");
		}
		if(Check.isNull(goods.getTypeCode())){
			return Result.failure(json, "商品类型不能为空", "typeCode_null");
		}
		if(Check.isNull(goods.getPicPaths())){
			return Result.failure(json, "商品图片不能为空", "pic_null");
		}
		
		// TODO FIXME 还需要检查库存数量
		
		BigDecimal priceBegin = goods.getAuctionPrice();//拍卖起拍价
		if(null != priceBegin){	//如果价格为空，则为议价
			priceBegin = priceBegin.setScale(0, BigDecimal.ROUND_HALF_UP);//设置保留为整数
			if(priceBegin.doubleValue() < 0 && priceBegin.doubleValue() > 1000000){//判读价格合理区间
			    return Result.failure(json, "拍卖起拍价只能在0元至100万元之间", "priceBegin_invalid");
			}
			goods.setAuctionPrice(priceBegin);
		}else{
			goods.setAuctionPrice(new BigDecimal(0));
		}
		
		BigDecimal postageFee = goods.getPostageFee();//运费
		if(null != postageFee){
			postageFee = postageFee.setScale(0, BigDecimal.ROUND_HALF_UP);//设置保留为整数
			if(postageFee.doubleValue() < 0 && postageFee.doubleValue() > 100000){//判读价格合理区间
			    return Result.failure(json, "运费只能在0元至10万元之间", "postageFee_invalid");
			}
			goods.setPostageFee(postageFee);
		}else{
			goods.setPostageFee(new BigDecimal(0));
		}
		
		BigDecimal shopPrice = goods.getShopPrice();
		if(null != shopPrice){	//如果价格为空，则为议价
			shopPrice = shopPrice.setScale(0, BigDecimal.ROUND_HALF_UP);//设置保留为整数
			if(shopPrice.doubleValue() < 0 && shopPrice.doubleValue() > 1000000){//判读价格合理区间
			    return Result.failure(json, "商品售价只能在0元至100万元之间", "shopPrice_invalid");
			}
			goods.setShopPrice(shopPrice);
		}
		return Result.success(json, null, null);
	}
	
	public JSONObject addGoods(JSONObject json, BaseUser user, BaseGoods goods, String apSerial, String basePath) throws Exception{
		//System.out.println("GoodsService_addGoods");
		validateGoods(json, goods);//验证
		if(Result.hasError(json))return json;
		Integer userId = user.getId();
		String username = user.getUsername();
		Integer shopId = user.getShopId();
		Date date = new Date();
		
		goods.setId(null);
		goods.setUserId(userId);
		goods.setMainStatus(1);//76：店铺中
		goods.setDeletedAt(null);
		goods.setDeletedBy(null);
		goods.setShopId(shopId);
		//goods.setPostageFee(new BigDecimal(1));//是否包邮（1,是 2，否）TODO 改为INT
		goods.setIsSevenReturn(1);//是否包退(1.包退2，不包退)
		goods.setGoodsName(Utf8mb4.filterOffUtf8Mb4(goods.getGoodsName().trim()));
		goods.setGoodsBrief(Utf8mb4.filterOffUtf8Mb4(goods.getGoodsBrief().trim()));
		String serial = CommonGenerator.getSerialByDate(BaseAssets.serial_prefix_goods);
		goods.setGoodsSn(serial);
		goods.setSerial(serial);
		goods.setCreatedBy(username);
		goods.setCreatedAt(date);
		goodsMapper.insert(goods);
		Integer goodsId = goods.getId();
		if(Check.isNull(goods.getPicPaths())){
			return Result.failure(json, "请上传藏品图片", "picPaths_null");
		}
		String filePaths[] = goods.getPicPaths().split(",");
		////System.out.println("GoodsService_addGoods_goodsPicPaths: "+goods.getPicPaths());
		List<BaseGoodsPicture> goodsPictureList = new ArrayList<BaseGoodsPicture>(filePaths.length);
		
		String endpoint = Const.oss_endpoint;
	    String accessKeyId = Const.oss_accessKeyId;
	    String accessKeySecret = Const.oss_accessKeySecret;
	    String bucketName = Const.oss_bucketName;
	    String bucketEndpoint = Const.oss_bucketEndpoint;
	    AliyunOSS oss = AliyunOSS.buildOSS(null, null, endpoint, accessKeyId, accessKeySecret, bucketName, bucketEndpoint);
	    
		for(int j = 0 ; j < filePaths.length ;j++){
			String mediaId = filePaths[j];
			BaseGoodsPicture goodsPicture = new BaseGoodsPicture();
			goodsPicture.setGoodsId(goodsId);
			goodsPicture.setSerial(CommonGenerator.getSerialByDate(BaseAssets.serial_prefix_goodsPicture));
			goodsPicture.setCreatedAt(date);
			goodsPicture.setCreatedBy(username);
			
			if(Check.isNotNull(mediaId) && !mediaId.equalsIgnoreCase("undefined")){//此处为微信服务器获取用户上传的图片
			    json = pictureService.getPicPathsByWxServerIds(json, mediaId, basePath, oss);
				String picPaths = json.getString("picPaths");
				if(Check.isNotNull(picPaths)){
					if(picPaths.startsWith(","))picPaths = picPaths.substring(1);
					//System.out.println("GoodsService_addGoods_goodsPicPath: "+picPaths);
					String localPath = "/file/wx/" + picPaths.substring(picPaths.lastIndexOf("/"), picPaths.length());
					goodsPicture.setLocalPicPath(localPath);
					goodsPicture.setOssPicPath(picPaths);
					goodsPicture.setPicPath(picPaths);
					goodsPicture.setIsCover(0);
					goodsPicture.setTypeCode("pic_type_goods");
					if(j == 0){
						goodsPicture.setIsCover(2);
					}
					goodsPictureList.add(goodsPicture);
				}
			}
		}
		if(Check.isNotNull(goodsPictureList)){
			goodsPictureMapper.insertBatch(goodsPictureList);
			goods.setUpdatedBy(username);
			goods.setUpdatedAt(date);
			goods.setPicPath(goodsPictureList.get(0).getPicPath());
			goods.setPicPaths(goodsPictureList.get(0).getPicPath());
			goodsMapper.updateByPrimaryKeySelective(goods);
		}
		
		if(Check.isNotNull(apSerial)){//专场编号不为空，将新上传的拍品添加到auction_goods
			AuctionProfession ap = apMapper.selectBySerial(apSerial);
			if(null == ap){
				json.put("goodsId", goods.getId());
				return Result.success(json);
			}
			AuctionGoods ag = new AuctionGoods();
			ag.setUserId(userId);
			ag.setAuctionId(ap.getId());
			ag.setGoodsId(goods.getId());
			ag.setGoodsSerial(goods.getSerial());
			ag.setPriceBegin(goods.getAuctionPrice());
			ag.setPostageFee(goods.getPostageFee());
			ag.setScansCount(1);
			ag.setSerial(CommonGenerator.getSerialByDate(Assets.serial_prefix_auctionGoods));
			ag.setMainStatus(1);
			ag.setCreatedAt(date);
			ag.setCreatedBy(username);
			agMapper.insertSelective(ag);
		}
		json.put("goodsId", goods.getId());
		return Result.success(json);
	}
	
	public JSONObject addGoodsForPC(JSONObject json, BaseGoods goods, String phone) throws Exception{
		validateGoods(json, goods);//验证
		if(Result.hasError(json))return json;
		Date date = new Date();
		Map<String,Object> map = CommonGenerator.getHashMap();
		if(!Check.isNotNull(phone)){
			return Result.failure(json, "请输入手机号码", "phone_null");
		}
		map.put("phone", phone);
		map.put("isPcUploadAllowed", 2);//允许上传
		List<BaseShop> shopList = shopMapper.selectListByCondition(map);
		BaseShop shop = null;
		BaseUser user = null;
		if(!Check.isNotNull(shopList)){
			return Result.failure(json, "手机号码不正确或者该手机号用户未允许电脑端代上传藏品", "shop_null");
		}
		shop = shopList.get(0);
		user = userMapper.selectByPrimaryKey(shop.getUserId());
		String username = user.getUsername();
		Integer shopId = shop.getId();
		goods.setId(null);
		goods.setMainStatus(76);//76：店铺中
		goods.setDeletedAt(null);
		goods.setDeletedBy(null);
		goods.setShopId(shopId);
		goods.setPostageFee(new BigDecimal(1));//是否包邮（1,是 2，否）TODO 改为INT
		goods.setIsSevenReturn(1);//是否包退(1.包退2，不包退)
		goods.setGoodsName(Utf8mb4.filterOffUtf8Mb4(goods.getGoodsName().trim()));
		goods.setGoodsDescription(Utf8mb4.filterOffUtf8Mb4(goods.getGoodsDescription().trim()));
		goods.setGoodsSn(CommonGenerator.getSerialByDate("g"));
		goods.setCreatedBy(username);
		goods.setCreatedAt(date);
		goodsMapper.insert(goods);
		Integer goodsId = goods.getId();
		String filePaths[] = goods.getPicPaths().split(",");
		List<BaseGoodsPicture> goodsPictureList = new ArrayList<BaseGoodsPicture>(filePaths.length);
		for(int j = 0 ; j < filePaths.length ;j++){
			BaseGoodsPicture goodsPicture = new BaseGoodsPicture();
			goodsPicture.setGoodsId(goodsId);
			goodsPicture.setSerial(CommonGenerator.getSerialByDate("gp"));
			goodsPicture.setCreatedAt(date);
			goodsPicture.setCreatedBy(username);
			goodsPicture.setPicPath(filePaths[j]);
			goodsPicture.setIsCover(0);
			if(j == 0){
				goodsPicture.setIsCover(2);
			}
			goodsPictureList.add(goodsPicture);
		}
		goodsPictureMapper.insertBatch(goodsPictureList);
		json.put("id",goods.getId());
		return Result.success(json);
	}

	public JSONObject getTuijianGoodsList(JSONObject json, Map<String, Object> map) {
		List<BaseGoods> goodsList = goodsMapper.selectListByCondition(map);
		Integer total = goodsMapper.selectCountByCondition(map);
		return Result.gridData(goodsList, total, json);
	}
	
}

